#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
#include "..//include//createvfs.h"
#include "..//include//n_ary.h"
#include "..//include//hash.h"
#include "..//include//vfs_errorcodes.h"

struct FD file_desc;
struct header headervar;

Tree mount_nary(char vfs_label[], char filename_g[]) {
	FILE *fp_m;
	char filepath[100], name[30];
	int i, pos = 0;
	char str[100];
	int used_des;
	//Tree root1;
	//printf("%s\n",filename_g);
	//printf("Blocks: %d\n",num_blocks);
	
	root = (Tree)malloc(sizeof(Tree));
  	strcpy (root -> node_label, "/");
  	strcpy (root -> path, "/");    
  	root -> left = NULL;
  	root -> right = NULL;   	
  	
  	//printf("Label 1: %s\n",vfs_label);
  	//root = root1;
  	
  	if(strcmp(vfs_label,"") == 0) {
  		printf("mountvfs_FAILURE %s\n",ERR_VFS_MOUNT_00);
		return 0;
  	}
  	//printf("Label 2: %s\n",vfs_label);
  	fp_m = fopen(filename_g, "rb+");
	if (fp_m == NULL) {
		printf("mountvfs_FAILURE %s\n",ERR_VFS_MOUNT_02);
		return 0;
	}	
	
	
	
	rewind(fp_m);
	fread(&headervar, sizeof(struct header), 1, fp_m);
	//printf("%s,%s\n",vfs_label, headervar.fs_label);
	if(strcmp(headervar.fs_label, vfs_label) != 0) {
		printf("mountvfs_FAILURE %s\n",ERR_VFS_MOUNT_01);
		return 0;
	}
		
	
	rewind (fp_m);
	fseek (fp_m, (LABEL_SIZE*sizeof(char) + 2*(sizeof(int)) + 2*sizeof(struct FD)), SEEK_SET);	
	
	
	//printf("\n num of used desc: %d",headervar.used_desc);
	for(i=3; i <= TOTAL_DESC; i++){	
			
		fread (&file_desc, sizeof(struct FD), 1, fp_m);	
		if(strcmp(file_desc.path,"\0")!=0){	
			strcpy(filepath,file_desc.path);					
  			root=insert(root,filepath);		
			rewind (fp_m);
			fseek (fp_m, (LABEL_SIZE*sizeof(char) + 2*(sizeof(int)) + i*sizeof(struct FD)), SEEK_SET);
  			strcpy(filepath,"");	
  		}	
	}
	
	//printf("In mount: No. of used des: %d\n", headervar.used_desc);
	
	
	
	// Writing the root details into the first FD
	strcpy(str,"");
	strcat(str,"/");
	//strcat(str, vfs_label);
	strcat(str, "\0");	
	
	
	rewind (fp_m);
	fseek (fp_m, (LABEL_SIZE*sizeof(char) + 2*(sizeof(int)) + sizeof(struct FD)), SEEK_SET);	
	fread (&file_desc, sizeof(struct FD), 1, fp_m);
	strcpy (file_desc.path, str);
	strcpy (file_desc.name, str);
	rewind (fp_m);
	fseek (fp_m, (LABEL_SIZE*sizeof(char) + 2*(sizeof(int)) + sizeof(struct FD)), SEEK_SET);
	fwrite (&file_desc, sizeof(struct FD), 1, fp_m);
	
	
	// Hash mount
	
	int hj;
	hj=mount_hash(vfs_label,filename_g);	
	
	
	fclose(fp_m);
	
	return root;
}
 

  
